import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class CountOfSmallerNumbersAfterSelf {
    public static void main(String[] args) {
        CountOfSmallerNumbersAfterSelf self = new CountOfSmallerNumbersAfterSelf();
        int[] arr = {5,2,6,1};
        self.countSmaller(arr);
    }

    int[] dp;
    int[] tmpNums;
    int[] tmpIndex;

    public List<Integer> countSmaller1(int[] nums) {
        int n = nums.length;
        dp = new int[n];
        tmpNums = new int[n];
        int[] index = new int[n];
        tmpIndex = new int[n];
        mergeSort(nums, 0, n - 1, index);
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i < n; i++) {
            list.add(dp[i]);
        }
        return list;
    }

    public List<Integer> countSmaller(int[] nums) {
        int n = nums.length;
        dp = new int[n];
        int[] index = new int[n];
        for (int i = 0; i < n; i++) {
            index[i] = i;
        }
        tmpNums = new int[n];
        tmpIndex = new int[n];
        mergeSort(nums, 0, n - 1, index);
        System.out.print(Arrays.toString(dp));
        return null;
    }

    public void mergeSort(int[] nums, int left, int right, int[] index) {
        if(left >= right) {
            return;
        }
        // 1.根据中间点划分左右部分
        int mid = left + ((right - left) >> 1);
        // [left, mid] [mid+1, right]
        mergeSort(nums, left, mid, index);
        mergeSort(nums, mid+1, right, index);

        // 2.合并的同时统计逆序对个数(降序)
        int cur1 = left, cur2 = mid+1, i = 0;
        while(cur1 <= mid && cur2 <= right) {
            if(nums[cur1] <= nums[cur2]) {
                tmpIndex[i] = index[cur2];
                tmpNums[i++] = nums[cur2++];
            }else {
                // nums[cur1] > nums[cur2]
                dp[index[cur1]] = dp[index[cur1]] + (right - cur2 + 1);
                tmpIndex[i] = index[cur1];
                tmpNums[i++] = nums[cur1++];
            }
        }

        while(cur1 <= mid) {
            tmpIndex[i] = index[cur1];
            tmpNums[i++] = nums[cur1++];
        }

        while(cur2 <= right) {
            tmpIndex[i] = index[cur2];
            tmpNums[i++] = nums[cur2++];
        }

        // 3.将辅助数组排好序的元素放回原数组中
        for(int j = 0; j < right - left + 1; j++) {
            index[j + left] = tmpIndex[j];
            nums[j + left] = tmpNums[j];
        }
    }

    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
